package com.xuelang.pipeline.app.resource.impl;

import com.xuelang.pipeline.app.resource.GitOperationService;
import com.xuelang.pipeline.client.common.constant.DictDTO;
import com.xuelang.pipeline.client.resource.dto.GitOperationDTO;
import com.xuelang.pipeline.domain.resource.GitOperation;
import com.xuelang.pipeline.domain.resource.service.GitDomainService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author liuyuan.ly
 * @since 2024/6/14 14:21
 */
@Service
public class GitOperationServiceImpl implements GitOperationService {

    @Autowired
    private GitDomainService domainService;

    @Override
    public List<DictDTO> getRemoteBranchList(GitOperationDTO operationDTO) {
        //校验特殊处理。前端组件需要返回null
        if (StringUtils.isEmpty(operationDTO.getCodeRepository())) {
            return new ArrayList<>();
        }
        if (StringUtils.isEmpty(operationDTO.getToken())) {
            return new ArrayList<>();
        }

        if ("{{componentCodeRepository}}".equals(operationDTO.getCodeRepository()) && "{{componentCodeToken}}".equals(operationDTO.getToken())) {
            return Stream.of(
                    new DictDTO("{{componentCodeBranch}}", "{{componentCodeBranch}}")
            ).collect(Collectors.toList());
        }

        GitOperation gitOperation = new GitOperation();
        gitOperation.setCodeRepository(operationDTO.getCodeRepository());
        gitOperation.setUsername("PRIVATE-TOKEN");
        gitOperation.setPassword(operationDTO.getToken());
        GitOperation remoteBranchList = domainService.getRemoteBranchList(gitOperation);
        List<String> remoteList = remoteBranchList.getRemoteList();
        if (StringUtils.isNotBlank(operationDTO.getQ())) {
            remoteList = remoteList.stream().filter(s -> s.contains(operationDTO.getQ())).collect(Collectors.toList());
        }

        return remoteList.stream().map(ref -> {
            DictDTO dictDTO = new DictDTO();
            dictDTO.setId(ref);
            dictDTO.setText(ref);
            return dictDTO;
        }).collect(Collectors.toList());
    }
}
